﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;//为   [DllImport("kernel32.dll")] [DllImport("hfrdapi.dll")]写法提供支持
namespace Super15693
{
    public partial class Form1 : Form
    {
        ///-----------句柄------------///
        IntPtr g_hDevice = (IntPtr)(-1); //g_hDevice must init as -1
        ///-----------系统------------///
        [DllImport("kernel32.dll")]
        static extern void Sleep(int dwMilliseconds);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_Open(ref IntPtr device,
                            UInt32 index,
                            UInt16 vid,
                            UInt16 pid);

        [DllImport("hfrdapi.dll")]
        static extern bool Sys_IsOpen(IntPtr device);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_Close(ref IntPtr device);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_SetBuzzer(IntPtr device, byte msec);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_SetAntenna(IntPtr device, byte mode);

        [DllImport("hfrdapi.dll")]
        static extern int Sys_InitType(IntPtr device, byte type);
        //========================= ISO15693 Card Function =========================
        [DllImport("hfrdapi.dll")]
        static extern int I15693_Inventory(IntPtr device, byte[] pData, ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_Inventorys(IntPtr device, byte[] pData, ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_GetSystemInformation(IntPtr device,
                                                      byte mode,
                                                      byte[] pUID,
                                                      byte[] pData,
                                                      ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_Select(IntPtr device, byte[] pUID);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_ResetToReady(IntPtr device, byte mode, byte[] pUID);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_StayQuiet(IntPtr device, byte[] pUID);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_GetBlockSecurity(IntPtr device,
                                                  byte mode,
                                                  byte[] pUID,
                                                  byte block,
                                                  byte number,
                                                  byte[] pData,
                                                  ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_Read(IntPtr device,
                                      byte mode,
                                      byte[] pUID,
                                      byte block,
                                      byte number,
                                      byte[] pData,
                                      ref byte pLen);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_Write(IntPtr device,
                                       byte mode,
                                       byte[] pUID,
                                       byte block,
                                       byte[] pData);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_LockBlock(IntPtr device,
                                           byte mode,
                                           byte[] pUID,
                                           byte block);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_WriteAFI(IntPtr device,
                                          byte mode,
                                          byte[] pUID,
                                          byte AFI);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_LockAFI(IntPtr device, byte mode, byte[] pUID);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_WriteDSFID(IntPtr device,
                                            byte mode,
                                            byte[] pUID,
                                            byte DSFID);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_LockDSFID(IntPtr device, byte mode, byte[] pUID);

        [DllImport("hfrdapi.dll")]
        static extern int I15693_DirectTransmit(IntPtr device,
                                                byte[] pCommand,
                                                byte cmdLen,
                                                byte[] pData,
                                                ref byte pMsgLg);


        /// <summary>
        /// //////////////DIY
        /// </summary>
        ///++++++++++++++++++++++++开始 hex-string+++++++++++++++++++++//
        #region byteHEX
        public static String byteHEX(Byte ib)
        {
            String _str = String.Empty;
            try
            {
                char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
                char[] ob = new char[2];
                ob[0] = Digit[(ib >> 4) & 0X0F];
                ob[1] = Digit[ib & 0X0F];
                _str = new String(ob);
            }
            catch (Exception)
            {
                new Exception("byteHEX error !");
            }
            return _str;

        }
        #endregion

        public static string ToHexString(byte[] bytes)
        {
            String hexString = String.Empty;
            for (int i = 0; i < bytes.Length; i++)
                hexString += byteHEX(bytes[i]);

            return hexString;
        }
        public static string ToHexString(byte[] bytes, byte len)//函数重载 上面
        {
            String hexString = String.Empty;
            for (int i = 0; i < len; i++)
                hexString += byteHEX(bytes[i]);

            return hexString;
        }
        ///++++++++++++++++++++++++结束+++++++++++++++++++++//
        ///
        ///+++++++++开始string--hex++++++++++//
        public static byte GetHexBitsValue(byte ch)
        {
            byte sz = 0;
            if (ch <= '9' && ch >= '0')
                sz = (byte)(ch - 0x30);
            if (ch <= 'F' && ch >= 'A')
                sz = (byte)(ch - 0x37);
            if (ch <= 'f' && ch >= 'a')
                sz = (byte)(ch - 0x57);

            return sz;
        }
        public static byte[] ToDigitsBytes(string theHex)
        {
            byte[] bytes = new byte[theHex.Length / 2 + (((theHex.Length % 2) > 0) ? 1 : 0)];
            for (int i = 0; i < bytes.Length; i++)
            {
                char lowbits = theHex[i * 2];
                char highbits;

                if ((i * 2 + 1) < theHex.Length)
                    highbits = theHex[i * 2 + 1];
                else
                    highbits = '0';

                int a = (int)GetHexBitsValue((byte)lowbits);
                int b = (int)GetHexBitsValue((byte)highbits);
                bytes[i] = (byte)((a << 4) + b);
            }

            return bytes;
        }
        ///+++++++++结束string--hex++++++++++//
        public Form1()
        {
            InitializeComponent();
            comboBox1.Text = "0";
            button5.Enabled = false;//太危险 不要锁定了 没办法解开
        }

       

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        //复位读卡器
        private void button1_Click(object sender, EventArgs e)
        {
            int status;
            string strError;
            unsafe//允许不安全
            {
                //NO.1:Check whether the reader is connected or not
                if (true == Sys_IsOpen(g_hDevice))
                {
                    //If the reader is already open , close it firstly
                    status = Sys_Close(ref g_hDevice);
                    if (0 != status)
                    {
                        strError = "Sys_Close failed !";
                        MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                //NO.2:Open
                status = Sys_Open(ref g_hDevice, 0, 0x0416, 0x8020);
                if (0 != status)
                {
                    strError = "Sys_Open failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


                //操作天线
                //NO.1:Close antenna of the reader
                status = Sys_SetAntenna(g_hDevice, 0);
                if (0 != status)
                {
                    strError = "Sys_SetAntenna failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Sleep(5); //Appropriate delay after Sys_SetAntenna operating 

                //Set the reader's working mode
                status = Sys_InitType(g_hDevice, (byte)'1');//!!!!Easy这里是(byte)'A'
                if (0 != status)
                {
                    strError = "Sys_InitType failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Sleep(5);

                //NO.2:Open antenna of the reader
                status = Sys_SetAntenna(g_hDevice, 1);
                if (0 != status)
                {
                    strError = "Sys_SetAntenna failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Sleep(5); //Appropriate delay after Sys_SetAntenna operating


                //============================ Success Tips ==========================
                //NO.1:Beep 200 ms
                status = Sys_SetBuzzer(g_hDevice, 20);
                if (0 != status)
                {
                    strError = "Sys_SetBuzzer failed !";
                    MessageBox.Show(strError, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int status;
            string UID;
            byte[] dataBuffer = new byte[64];
            byte len = 0;

            //====== Check whether the reader is opened or not =======
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("The device has not been opened yet !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //====================== Read UID ========================
            status = I15693_Inventory(g_hDevice, dataBuffer, ref len);
            //dataBuffer[]: 1 byte DSFID + 8 bytes UID
            if (status != 0)
            {
                MessageBox.Show("I15693_Inventory failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            byte[] bytesData = new byte[64];
            for (int i = 0; i < 8; i++)
                bytesData[i] = Marshal.ReadByte(dataBuffer, i + 1);
            UID = ToHexString(bytesData, 8);
            textBox1.Text = UID;
        }

       

        //读卡
        private void button3_Click(object sender, EventArgs e)
        {
            int status;
            byte[] dataBuffer = new byte[64];
            byte len = 0;
            byte block;
            string tagdata;

            //====== Check whether the reader is opened or not ========
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("The device has not been opened yet !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //=================== Read block data =====================
            //准备参数1 卡的UID
            byte[] bytesUID = ToDigitsBytes(textBox1.Text);
            //准备参数2 哪一个块儿
            block = Convert.ToByte(comboBox1.Text);

            status = I15693_Read(g_hDevice, 0x02, bytesUID, block, 1, dataBuffer, ref len);
            if (status != 0)
            {//失败
                MessageBox.Show("I15693_Read failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //成功
            byte[] bytesData = new byte[64];
            for (int i = 0; i < len; i++)
                bytesData[i] = Marshal.ReadByte(dataBuffer, i);
            tagdata = ToHexString(bytesData, len);
            textBox4.Text = tagdata;



            //=================== Read block security ===================
            status = I15693_GetBlockSecurity(g_hDevice, 0x02, bytesUID, block, 1, dataBuffer, ref len);
            if (status != 0)
            {
                MessageBox.Show("I15693_GetBlockSecurity failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            bytesData = new byte[64];
            for (int i = 0; i < len; i++)
                bytesData[i] = Marshal.ReadByte(dataBuffer, i);
            tagdata = ToHexString(bytesData, len);

            textBox5.Text = tagdata;
        }
        
        
        //写卡
        private void button4_Click(object sender, EventArgs e)
        {
            int status;
            byte[] dataBuffer = new byte[64];
            byte block;

            //======= Check whether the reader is opened or not ========
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("The device has not been opened yet !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //=================== Write block data =====================
            //准备参数1 卡的UID
            byte[] bytesUID = ToDigitsBytes(textBox1.Text);
            //准备参数2 哪一个块儿
            block = Convert.ToByte(comboBox1.Text);
            //准备参数3 写啥
            dataBuffer = ToDigitsBytes(textBox4.Text);

            status = I15693_Write(g_hDevice, 0x02, bytesUID, block, dataBuffer);
            if (status != 0)
            {//失败
                MessageBox.Show("I15693_Write failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //成功
            Sys_SetBuzzer(g_hDevice, 20);

        }

        private void button5_Click(object sender, EventArgs e)
        {
            int status;
            byte[] dataBuffer = new byte[64];
            byte block;

            //====== Check whether the reader is opened or not =======
            if (true != Sys_IsOpen(g_hDevice))
            {
                MessageBox.Show("The device has not been opened yet !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //===================== Lock block =======================
            //准备参数1 卡的UID
            byte[] bytesUID = ToDigitsBytes(textBox1.Text);
            //准备参数2 哪一个块儿
            block = Convert.ToByte(comboBox1.Text);

            if (DialogResult.Cancel == MessageBox.Show("Are you sure to lock the block? After locking, the block contents cannot be changed anymore.",
                                                       "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
                return;

            status = I15693_LockBlock(g_hDevice, 0x02, bytesUID, block);
            if (status != 0)
            {
                MessageBox.Show("I15693_LockBlock failed !", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
        //翻页
        private void button6_Click(object sender, EventArgs e)
        {
            Form2 Sub = new Form2();
            Sub.Show();                       //显示子对话框内容 
        }
    }
}
